<template>
  <div class="wechat-reward-config">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="180px"
      size="default"
    >
      <el-form-item
        label="开启状态"
        prop="enableStatus"
      >
        <el-switch
          v-model="formData.enableStatus"
          :active-text="'开启'"
          :inactive-text="'关闭'"
        />
      </el-form-item>

      <el-form-item
        label="红包类型"
        prop="rewardType"
      >
        <el-radio-group v-model="formData.rewardType">
          <el-radio :value="1">拼手气红包</el-radio>
          <el-radio :value="2">普通红包</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="总金额"
        prop="totalAmount"
      >
        <el-input-number
          v-model="formData.totalAmount"
          :min="0"
          :step="1"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input-number>
      </el-form-item>

      <el-form-item
        label="红包个数"
        prop="count"
      >
        <el-input-number
          v-model="formData.count"
          :precision="0"
          class="number-width"
        />
      </el-form-item>

      <el-form-item
        v-if="formData.rewardType === 1"
        label="单个红包金额范围"
      >
        <el-input-number
          v-model="formData.minAmount"
          :min="0.3"
          :precision="1"
          :step="0.1"
          class="number-width mr10"
        />
        至
        <el-input-number
          v-model="formData.maxAmount"
          :max="formData.totalAmount"
          :precision="1"
          :step="0.1"
          class="number-width ml10"
        ></el-input-number>
      </el-form-item>

      <el-form-item
        label="抽中概率"
        prop="probability"
      >
        <el-input-number
          v-model="formData.probability"
          :max="100"
          :min="0"
          :step="1"
        >
          <template #suffix>
            <span>%</span>
          </template>
        </el-input-number>
      </el-form-item>

      <el-form-item label="抽奖条件">
        <div class="w100">
          <div class="condition-item">
            <el-checkbox
              v-model="formData.enableWxClaimLimit"
              value="oneTime"
            >
              每个微信号只能抽一次
            </el-checkbox>
          </div>
          <div class="condition-item">
            <el-checkbox
              v-model="formData.enableWxAuditRelease"
              value="verifyPublisher"
            >
              通过发布者审核后再发放
            </el-checkbox>
            <data-filter
              ref="dataFilterRef"
              :fields="formFillFields"
              :form-data-filter="formData.conditionConfig"
              :form-key="sourceId"
              class="w100"
            />
          </div>
        </div>
      </el-form-item>

      <el-form-item
        label="红包发送方名称"
        prop="sendName"
        required
      >
        <el-input
          v-model="formData.sendName"
          class="input-width"
          clearable
          placeholder="请输入红包发送方名称"
        />
      </el-form-item>

      <el-form-item
        label="红包祝福语"
        prop="wishing"
        required
      >
        <el-input
          v-model="formData.wishing"
          class="input-width"
          clearable
          placeholder="请输入红包祝福语"
        />
      </el-form-item>

      <el-form-item
        label="活动名称"
        prop="actName"
        required
      >
        <el-input
          v-model="formData.actName"
          class="input-width"
          clearable
          placeholder="请输入活动名称"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="handleSubmit"
        >
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import type { FormInstance } from "element-plus";
import { DrawRedPacketConfigEntity, getRedPacketConfig, saveRedPacketConfig } from "@/api/project/lottery";
import { MessageUtil } from "@/utils/messageUtil";
import { i18n } from "@/i18n";
import DataFilter from "@/views/form/data/filter/index.vue";
import { storeToRefs } from "pinia";
import { useFormInfo } from "@/stores/formInfo";
import { saveSettingRequest } from "@/api/project/setting";

onMounted(() => {
  getActivitiesData();
});

const formRef = ref<FormInstance>();

const formInfoStore = useFormInfo();

const { formFillFields } = storeToRefs(formInfoStore);

interface Props {
  sourceId: string;
  sourceType: string;
}

const props = defineProps<Props>();

const formData = ref<DrawRedPacketConfigEntity>({
  id: 0,
  sourceId: props.sourceId,
  sourceType: props.sourceType,
  enableStatus: false,
  rewardType: 1,
  totalAmount: 200,
  count: 1,
  minAmount: 0.3,
  maxAmount: 200,
  probability: 100,
  enableWxClaimLimit: false,
  enableWxAuditRelease: false,
  conditionConfig: {},
  sendName: "",
  wishing: "",
  actName: "",
  remark: ""
});

const rules = {
  rewardType: [{ required: true, message: "请选择红包类型" }],
  totalAmount: [
    { required: true, message: "请输入总金额" },
    { type: "number", min: 0.3, message: "总金额必须大于0.3元" }
  ],
  count: [
    { required: true, message: "请输入红包个数" },
    { type: "number", min: 1, message: "红包个数必须大于0" }
  ],
  probability: [
    { required: true, message: "请输入抽中概率" },
    { type: "number", min: 0, max: 100, message: "概率范围为0-100" }
  ],
  sendName: [{ required: true, message: "请输入红包发送方名称", trigger: "blur" }],
  wishing: [{ required: true, message: "请输入红包祝福语", trigger: "blur" }],
  actName: [{ required: true, message: "请输入活动名称", trigger: "blur" }]
};

const emit = defineEmits(["close"]);

const dataFilterRef = ref<any>();

const handleSubmit = async () => {
  if (!formRef.value) return;

  // 验证红包参数
  const { totalAmount, count, minAmount, maxAmount, rewardType } = formData.value;

  // 验证平均金额不能小于0.3元
  const avgAmount = totalAmount / count;
  if (avgAmount < 0.3) {
    MessageUtil.error("单个红包平均金额不能小于0.3元");
    return;
  }

  // 如果是拼手气红包，验证金额范围
  if (rewardType === 1) {
    // 验证最小金额不能大于最大金额
    if (minAmount >= maxAmount) {
      MessageUtil.error("最小金额必须小于最大金额");
      return;
    }

    // 验证最大金额不能小于总金额
    if (maxAmount < totalAmount) {
      MessageUtil.error("最大金额不能小于总金额");
      return;
    }

    // 验证最小金额 * 红包个数不能大于总金额
    if (minAmount * count > totalAmount) {
      MessageUtil.error("最小金额设置过大，无法满足红包个数要求");
      return;
    }

    // 验证最小金额 * 红包个数不能大于总金额
    if (maxAmount * count < totalAmount) {
      MessageUtil.error("最大金额设置过小，无法满足红包个数要求");
      return;
    }
  }

  // 普通红包验证（固定金额）
  if (rewardType === 2) {
    // 转换为分处理两位小数
    const amountInCents = totalAmount * 100;
    const singleAmount = amountInCents / count;

    // 检查是否能够平均分配（是否为整数）
    if (!Number.isInteger(singleAmount)) {
      MessageUtil.error("红包金额无法均分");
      return;
    }
  }
  // 条件
  formData.value.conditionConfig = dataFilterRef.value.getFilterData();

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      saveRedPacketConfig(formData.value).then(() => {
        getActivitiesData();
        // 打开仅在微信填写
        if (formData.value.enableStatus) {
          saveSettingRequest({
            formKey: props.sourceId,
            onlyWxWrite: true,
            recordWxUser: true
          });
        }
        MessageUtil.success(i18n.global.t("common.saveSuccess"));
        emit("close");
      });
    } else {
      console.error("验证失败:", fields);
    }
  });
};

const getActivitiesData = () => {
  getRedPacketConfig(props.sourceType, props.sourceId).then(res => {
    if (res.data) {
      formData.value = res.data;
    }
  });
};

const handleFilterChange = (filter: any) => {
  // formData.value.conditionConfig = {
  //   ...filter,
  //   conditionList: filter.conditionList
  //     .filter((item: any) => {
  //       return item.formItemId && item.method;
  //     })
  //     .map((item: any) => {
  //       return {
  //         formItemId: item.formItemId,
  //         method: item.method,
  //         value: item.value
  //       };
  //     })
  // };
};
</script>

<style lang="scss" scoped>
.mini-width {
  width: 150px;
}

.number-width {
  width: 250px;
}

.input-width {
  width: 300px;
}
</style>
